<template>
  <common>
    <div class="login-container">
      <el-card>
        <h1>登录</h1>
        <transition name="el-fade-in-linear">
          <el-form
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            ref="loginRef"
            :inline="false"
            @keyup.enter="handleLogin"
          >
            <el-form-item prop="username">
              <el-input
                v-model.trim="loginForm.username"
                size="large"
                placeholder="用户名"
              >
                <template #prepend>
                  <el-icon :size="20">
                    <Avatar />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model.trim="loginForm.password"
                size="large"
                show-password
                placeholder="密码"
              >
                <template #prepend>
                  <el-icon :size="20">
                    <Lock />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="verifyCode" v-if="captchaMode.value">
              <el-input
                v-model="loginForm.verifyCode"
                size="large"
                placeholder="验证码"
                style="width: 63%"
              >
                <template #prepend>
                  <el-icon :size="20">
                    <Key />
                  </el-icon>
                </template>
              </el-input>
              <div class="login-code">
                <img :src="codeUrl" @click="getCode" class="login-code-img" />
              </div>
            </el-form-item>
            <div style="float: left">
              <el-checkbox
                v-model="loginForm.rememberMe"
                style="margin: 0px 0px 25px 1px"
                >记住密码</el-checkbox
              >
            </div>
            <el-form-item style="width: 100%">
              <el-button
                :loading="loading"
                class="login-submit"
                size="large"
                type="primary"
                @click.prevent="handleLogin"
              >
                <span v-if="!loading">登 录</span>
                <span v-else>登 录 中...</span>
              </el-button>
            </el-form-item>
          </el-form>
        </transition>
      </el-card>
    </div>
  </common>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import Cookies from "js-cookie";
import Common from "@/components/Common";
import * as loginApi from "../api/loginApi";

const store = useStore();
const router = useRouter();
const { proxy } = getCurrentInstance();
const codeUrl = ref("");
const loading = ref(false);
const redirect = ref(undefined);
const captchaMode = ref(false);

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
  verifyCode: "",
  verifyCodeUUID: "",
});

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  verifyCode: [{ required: true, trigger: "change", message: "请输入验证码" }],
};

/** 登录 */
const handleLogin = () => {
  proxy.$refs.loginRef.validate((valid) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在cookie中设置记住用户明和名命
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", loginForm.value.password, { expires: 30 });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用action的登录方法
      store
        .dispatch("login", loginForm.value)
        .then(() => {
          console.log("redirect.value------------------------------------->");
          console.log(redirect.value);
          console.log("redirect.value------------------------------------->");
          router.push({ path: redirect.value || "/" });
        })
        .catch(() => {
          loading.value = false;
          // 重新获取验证码
          if (captchaMode.value) {
            getCode();
          }
        });
    }
  });
};

/** 查询是否开启验证码 */
const getCaptchaMode = () => {
  loginApi.getCaptchaMode().then((res) => {
    captchaMode.value =
      res.data.captchaMode === undefined ? true : res.data.captchaMode;
  });
};

/** 获得验证码 */
const getCode = () => {
  loginApi.getCodeImg().then((res) => {
    if (captchaMode.value === true) {
      console.log("开启验证码");
      codeUrl.value = res.data.imgBase64;
      loginForm.value.verifyCodeUUID = res.data.uuid;
    }
  });
};

/** 获得Cookie */
function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : password,
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
  };
}
getCaptchaMode();
getCode();
getCookie();
</script>

<style lang="scss" scoped>
.login-container {
  position: absolute;
  z-index: 1;
  width: 400px;
  top: 50%;
  left: 100px;
  transform: translateY(-50%);
  transition: all 1s;
  min-height: 273px;
  text-align: center;

  h1 {
    font-size: 24px;
    transition: all 1s;
    font-weight: bold;
    margin-bottom: 36px;
  }

  .login-form {
    .login-submit {
      width: 100%;
    }

    .login-code {
      width: 33%;
      height: 40px;
      float: right;

      img {
        cursor: pointer;
        vertical-align: middle;
      }
    }

    .login-code-img {
      height: 40px;
      width: 130px;
      padding-left: 12px;
      //border: 1px solid #ccc;
    }

    :deep(.el-input-group__prepend) {
      padding: 0 10px;
    }
  }
}
</style>
